﻿#ifndef __COMPLEX_H__
#define __COMPLEX_H__

#include <iostream>
using namespace std;


class complex
{
public:
    // 构造函数
    complex(double _re = 0.0, double _im = 0.0)
    : re(_re), im(_im)
    { }

    // 拷贝构造
    complex(const complex& c)
    { *this = c; }

    // 拷贝赋值
    complex& operator = (const complex& c);

    // +=,-=操作符重载
    complex& operator += (const complex& c);
    complex& operator += (double re);
    complex& operator -= (const complex& c);
    complex& operator -= (double re);

    inline double real() const { return re; }
    inline double imag() const { return im; }

    friend complex& __doapl(complex* ths, const complex& r);

private:
    double re, im;
};

complex& complex::operator = (const complex& c)
{
    // 自赋值检查
    if(this == &c)
        return *this;
    
    this->re = c.re;
    this->im = c.im;
    return *this;
}

complex& __doapl(complex* ths, const complex& r)
{
    ths->re += r.re;
    ths->im += r.im;
    return *ths;
}

inline complex& complex::operator += (const complex& c)
{
    return __doapl(this, c);
}
inline complex& complex::operator += (double re)
{
    return __doapl(this, complex(re));
}
inline complex& complex::operator -= (const complex& c)
{
    return __doapl(this, complex(-c.re, -c.im));
}
inline complex& complex::operator -= (double re)
{
    return __doapl(this, complex(-re));
}


// + 操作符重载
inline complex operator + (const complex& c, const complex& r)
{
    return complex(c.real() + r.real(), c.imag() + r.imag());
}
inline complex operator + (const complex& c, double re)
{
    return complex(c.real() + re, c.imag());
}
inline complex operator + (double re, const complex& c)
{
    return complex(c.real() + re, c.imag());
}

// << 操作符重载
inline ostream& operator << (ostream& out, const complex& c)
{
    return out << "(" << c.real() << ", " << c.imag() << ")";
}

#endif // __COMPLEX_H__
